<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use think\Cache;
use think\Db;
use think\Hook;

/**
 * 用户行为统计
 */
class Statistics extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     * @return void
     */

    /**
     * 由于前端在发起虚拟支付的时候，经常会遇到弹出“用户取消支付”的BUG，前端又无法重现，所以增加了一个错误日志的存储方法
     * 用于后面查看日志，看看用户到底发生了什么导致这个BUG
     * @return void
     */
    public function xuni_pay_error_log()
    {

        $params['buyQuantity'] = input('buyQuantity');;
        $params['errCode'] = input('errCode');;
        $params['errMsg'] = input('errMsg');;
        $params['order_id'] = input('order_id');;
        $params['pay_sig'] = input('pay_sig');
        $params['pay_status'] = input('pay_status');
        $params['signature'] = input('signature');
        $params['source'] = input('source');


        $error_info = json_encode($params,JSON_UNESCAPED_UNICODE);
        file_put_contents("log/xuni_pay_error_log".date('Ymd').".txt",date('Y-m-d H:i:s').$error_info.PHP_EOL,FILE_APPEND);
        file_put_contents("log/xuni_pay_error_log".date('Ymd').".txt","——————————————————————————————————————————————————————————————".$error_info.PHP_EOL,FILE_APPEND);
        $this->success('ok');

    }

    /**
     * 搜集用户行为
     * @ApiMethod (POST)
     * @param string $user_id  用户id
     * @param string $start_time  本次行为开始的时间(Y-m-d H:i:s)的格式
     * @param string $random  本次行为的唯一标识
     * @param string $episode_info_id  最新观看的集数ID
     * @param string $episode_script_id  最新观看的剧本ID
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     */
    public function statistics()
    {
        $data = [];
        $data['user_id'] = input('user_id');
        $data['start_time'] = input('start_time');
        $data['end_time'] = input('end_time');
        $data['random'] = input('random');
        $data['episode_info_id'] = input('episode_info_id');
        $data['episode_script_id'] = input('episode_script_id');
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['end_time'] = date('Y-m-d H:i:s');

        if(!empty($data['random'])){
            $log = DB::name("statistics")->where(['random'=>$data['random'],'user_id'=>$data['user_id']])->find();
            if(empty($log)){
                $res = DB::name("statistics")->insert($data);
            }else {
                $res = DB::name("statistics")->where(['id'=>$log['id']])->update($data);
            }
            $this->success('ok', $res);
        }else {
            $this->error("random不能为空");
        }
    }

    /**
     * 查看统计
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showStatistics(){
        echo "<html>";
        echo "<body>";
        echo "<input type='date' onchange='reload(this.value)'>日期<br/>";
        echo "<button onclick='window.location.href=\"https://shsh.vxmeng.com/api/statistics/showStatistics\"'>重置</button>";
        $script = "<script type='application/javascript'> function reload(url){window.location.href = 'https://shsh.vxmeng.com/api/statistics/showStatistics?date='+url}</script>";
        echo $script;

        $date = input('date');
        if(empty($date)){
            echo "<h1>支付情况</h1>";
            $this->showPay_func(0);
            $this->showPay_func(1);
            $this->showPay_func(2);
            echo "<hr/>";
            echo "<h1>《嘶哈，这个男人有点帅！》</h1>";
            $this->showStatistics_func_v2(0);
            $this->showStatistics_func_v2(1);
            $this->showStatistics_func_v2(2);
        }else {
            echo "<h1>支付情况</h1>";
            $this->showPay_func(0,$date);
            echo "<hr/>";
            echo "<h1>《嘶哈，这个男人有点帅！》</h1>";
            $this->showStatistics_func_v2(0,$date);
        }

        echo "</body>";
        echo "</html>";
    }

    /**
     * 给前端调用并返回统计数据的接口
     * @return null
     */
    public function showStatisticsApi(){
        $date = input('date');
        if (!$this->isValidDate($date)) {
            $this->error("日期格式错误:Y-m-d");
        }

        $where_script = ['episode_script_id'=>6];

        $createtime_start = strtotime(date('Y-m-d 00:00:00',strtotime($date)));
        $createtime_end = strtotime(date('Y-m-d 23:59:59',strtotime($date)));

        $user_ids = DB::name("user")->where("createtime",">=",$createtime_start)->where("createtime","<=",$createtime_end)->column("id");

        $total_people_num = count($user_ids);//当天的注册人数

        $info_ids = DB::name('episode_info')->where($where_script)->column("id");//所有剧集ID

        if($total_people_num > 0){
            $sql = "SELECT count(distinct user_id) as num,episode_info_id FROM 2000_cn.fa_episode_look where episode_script_id = 6 and user_id in (".implode(",", $user_ids).") and episode_info_id in (".implode(",", $info_ids).") group by episode_info_id";
            $list = DB::query($sql);

            if($total_people_num > 0){
                foreach ($info_ids as $info_id){
                    $num = 0;

                    foreach ($list as $l){
                        if($info_id == $l['episode_info_id']){
                            $num = $l['num'];
                            break;
                        }
                    }

                    $result[$info_id]['num'] = $num;
                    $result[$info_id]['percentage'] = round($num / $total_people_num * 100,2);

                }
            }
        }else {
            foreach ($info_ids as $info_id){
                $result[$info_id]['num'] = 0;
                $result[$info_id]['percentage'] = 0;
            }
        }
        $result['total_people_num'] = $total_people_num;//当天的注册人数

        return $this->success('',$result);
    }

    /**
     * 用于查询并展示统计信息的方法
     * @param $before_day_num
     * @return void
     */
    protected function showStatistics_func_v2($before_day_num = "2",$date = ""){
        $where_script = ['episode_script_id'=>6];

        $nameAndIds = DB::name("episode_info")->where($where_script)->column("name","id");
        $fileAndIds = DB::name("episode_info")->where($where_script)->column("file","id");

        if(empty($date)){
            $createtime_start = strtotime(date('Y-m-d 00:00:00',strtotime("-{$before_day_num} days")));
            $createtime_end = strtotime(date('Y-m-d 23:59:59',strtotime("-{$before_day_num} days")));
        }else {
            $createtime_start = strtotime(date("{$date} 00:00:00"));
            $createtime_end = strtotime(date("{$date} 23:59:59"));
        }



        if(empty($date)){
            switch ($before_day_num){
                case "2":
                    echo "<h3>【前天】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
                case "1":
                    echo "<h3>【昨天】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
                case "0":
                    echo "<h3>【今天】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
                default:
                    echo "<h3>【{$before_day_num}天前】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
            }
        }else {
            echo "<h3>".date('Y-m-d',$createtime_start)."</h3>";
        }


        $user_ids = DB::name("user")->where("createtime",">=",$createtime_start)->where("createtime","<=",$createtime_end)->column("id");
        $total_people_num = count($user_ids);
        echo "注册人数=".$total_people_num."<br/>";

        if($total_people_num > 0){
            $info_ids = $this->getInfo_ids();

            $sql = "SELECT count(distinct user_id) as num,episode_info_id FROM 2000_cn.fa_episode_look where episode_script_id = 6 and user_id in (".implode(",", $user_ids).") and episode_info_id in (".implode(",", $info_ids).") group by episode_info_id";
            $list = DB::query($sql);

            if($total_people_num > 0){
                foreach ($info_ids as $info_id){
                    $num = 0;

                    foreach ($list as $l){
                        if($info_id == $l['episode_info_id']){
                            $num = $l['num'];
                            break;
                        }
                    }

                    $name = $nameAndIds[$info_id];
                    $file = $fileAndIds[$info_id];
                    $round = round($num / $total_people_num * 100,2);
                    if(!empty($file)){
                        $arr1 = explode("-",$file);
                        $arr2 = explode("/",$arr1[0]);
                        $file_name = $arr2[(count($arr2)-1)];
                    }else {
                        $file_name = "";
                    }
                    echo "有{$num}人({$round}%)看过《{$file_name}.{$name}》";
                    echo "<br/>";
                }
            }
        }

        echo "<br/><br/>";
    }

    protected function showPay_func($before_day_num = "2",$date = "")
    {
        if(empty($date)){
            $createtime_start_date = date('Y-m-d 00:00:00',strtotime("-{$before_day_num} days"));
            $createtime_end_date = date('Y-m-d 23:59:59',strtotime("-{$before_day_num} days"));

            $createtime_start = strtotime($createtime_start_date);
            $createtime_end = strtotime($createtime_end_date);
        }else {
            $createtime_start_date = $date." 00:00:00";
            $createtime_end_date = $date." 23:59:59";

            $createtime_start = strtotime($createtime_start_date);
            $createtime_end = strtotime($createtime_end_date);
        }


        if(empty($date)){
            switch ($before_day_num){
                case "2":
                    echo "<h3>【前天】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
                case "1":
                    echo "<h3>【昨天】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
                case "0":
                    echo "<h3>【今天】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
                default:
                    echo "<h3>【{$before_day_num}天前】(".date('Y-m-d',$createtime_start).")</h3>";
                    break;
            }
        }else {
            echo "<h3>".date('Y-m-d',$createtime_start)."</h3>";
        }



        $xuni_success = DB::name("user_recharge")->where("create_time",'>=',$createtime_start_date)->where("create_time","<=",$createtime_end_date)->where("status","=",2)->where("device_type","=",1)->count();
        $normal_success = DB::name("user_recharge")->where("create_time",'>=',$createtime_start_date)->where("create_time","<=",$createtime_end_date)->where("status","=",2)->where("device_type","=",2)->count();

        $xuni_pay_success_do_fail = DB::name("user_recharge")->where("create_time",'>=',$createtime_start_date)->where("create_time","<=",$createtime_end_date)->where("status","=",3)->where("is_real_order","=",1)->count();

        echo "虚拟支付成功{$xuni_success}笔，普通支付成功{$normal_success}笔，虚拟支付中付款成功但充值失败的订单数={$xuni_pay_success_do_fail}";
        echo "<br/>";
    }

    /**
     * 按照顺序获得流程图每一集视频的ID
     * @return int[]
     */
    protected function getInfo_ids()
    {
        $info_ids = [
            12//昨夜故事
            ,241//摸
            ,242//不摸

            ,13//好久不见
            ,244//帮忙
            ,243//不帮忙

            ,16//毒舌祁遇
            ,18//虐猫怪人
            ,245//大声制止
            ,246//悄悄取证

            ,19//过往云烟
            ,247//嫌弃走开
            ,248//加帅哥微信
            ,249//哥哥在这
            ,250//搪塞过去
            ,251//说出真实目的

            ,21//祁遇刁难
            ,22//小心思
            ,23//再战祁遇
            ,24//暗示送礼物
            ,39//屡败屡战
            ,40//哥哥生日
            ,42//爱心晚餐
            ,45//温馨礼物
            ,46//投其所好
            ,253//买模型成品
            ,252//精心组装模型
            ,52//死傲娇男
            ,254//勇于承担错误
            ,255//管她呢~哼~
            ,53//帆船模型
            ,60//拨云见日
            ,257//和善温柔
            ,256//表面不一
            ,258//和周晟言走
            ,259//赴季京泽约
            ,68//甜蜜乐园
            ,67//酒吧重逢
            ,70//重逢竹马
            ,260//提议让路之遥搬入你家
            ,261//为路之遥订酒店
            ,75//你忘了
            ,76//路之遥不请自来
            ,77//哥哥和路之遥吃饭较劲
            ,81//哥哥不得不回家
            ,82//争宠
            ,263//推开门看看
            ,262//上床睡觉
            ,86//做早餐
            ,264//吃哥哥的西式早餐
            ,265//吃路之遥重庆小面
            ,89//神秘的Jason
            ,90//季京泽Jason
            ,91//上谁的车
            ,267//上祁遇的车
            ,266//跟季京泽走
            ,94//暗暗后悔
            ,97//我还记得
            ,99//你怎么了
            ,268//购买医药箱
            ,269//当场推开
            ,270//静观其变
            ,105//照顾好他
            ,107//花花在哪
            ,272//婉拒花花
            ,271//看花花答应
            ,110//宋时进门
            ,273//收起路之遥鞋子
            ,274//不收路之遥的鞋
            ,113//拿下宋时
            ,114//合作愉快
            ,275//婉拒看望宋时
            ,276//同意看望宋时
            ,118//看望宋时
            ,119//温暖冲剂
            ,278//为他盖上毯子
            ,277//叮嘱他吃药
            ,122//爱情选项
            ,280//答应哥哥邀请
            ,279//和路之遥外出约会
            ,125//烛光晚餐
            ,127//成长男孩
            ,128//注意啊
            ,129//游戏结束
            ,282//跟随路之遥
            ,281//独自离开
            ,134//由你负责
            ,321//宋时邀约
            ,135//你的意见
            ,284//当场答应
            ,283//含蓄婉拒
            ,138//找灵感
            ,285//答应季京泽的邀约
            ,286//在乎之前宋时的提议
            ,141//答案
            ,322//画图
            ,144//来我家
            ,288//选择公共地方
            ,287//去宋时家
            ,147//发现宋时喝闷酒
            ,148//修补模型
            ,289//主动帮忙组装
            ,290//装作不知道
            ,151//危机
            ,291//当场确定去营救路之遥
            ,293//先稳住对方 再另想办法
            ,292//假装不认识路之遥
            ,155//不要过来
            ,160//暖男祁遇
            ,161//最重要的
            ,163//麻烦你了
            ,164//宋时黑料
            ,165//流言蜚语
            ,297//坚持负起责任
            ,296//见机行事
            ,168//你去哪了
            ,171//背负着的
            ,299//理解宋时
            ,176//害羞祁遇
            ,177//宋时车祸
            ,300//让季京泽救场
            ,301//将问题甩给祁遇
            ,180//我又来陪你了
            ,181//来者不拒
            ,182//注意身体
            ,183//无法面对
            ,184//电梯事故
            ,185//独处
            ,186//真相大白
            ,302//不听季京泽的解释
            ,303//听听季京泽的解释
            ,304//出去赴约

            ,196//宋时告白
            ,198//同居故事
            ,199//宋时烦恼
            ,310//安全感
            ,311//主动要求澄清
            ,203//再见了

            ,211//季京泽告白
            ,213//争夺战
            ,214//我是正宫

            ,204//祁遇告白
            ,205//你干什么
            ,207//奇怪反差
            ,208//抗争祁母

            ,215//路之遥告白
            ,218//接受拥吻
            ,223//你去哪了
            ,219//我更爱你
            ,224//医院误解
            ,221//嫁给我吧
            ,226//不是弟弟
            ,227//一家人

            ,228//周晟言告白
            ,312//答应哥哥告白
            ,313//婉拒哥哥告白
            ,232//结婚了！
            ,238//想我没啊
            ,233//恭喜哥哥
            ,234//好妹妹！
            ,236//回到从前

            ,326//片尾
        ];
        return $info_ids;
    }



    function isValidDate($date, $format = 'Y-m-d') {
        $d = \DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) === $date;
    }
}
